package testWeb;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import conn.Connection1;
import conn.img;

/**
 * Servlet implementation class FindImgServlet
 */
@WebServlet(description = "分页展示图图片", urlPatterns = { "/FindImgServlet" })
public class FindImgServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FindImgServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 当前页码
		int currPage = 1;
		// 判断传递页码是否有效
		if(request.getParameter("page") != null){
			// 对当前页码赋值 
			currPage = Integer.parseInt(request.getParameter("page"));
		}
		// 实例化ProductDao
		Connection1 dao = new Connection1();
		// 查询所有商品信息
		List<img> list = dao.find(currPage);
		// 将list放置到request之中
		//[img [imgName=QQ图片20160714151244.png, imgSrc=images/QQ图片20160714151244.png, id=148], ......]
		request.setAttribute("list", list);
		// 总页数
		int pages ;
		// 查询总记录数
		int count = dao.findCount();
		// 计算总页数
		if(count % img.PAGE_SIZE == 0){
			// 对总页数赋值
			pages = count / img.PAGE_SIZE;
		}else{
			// 对总页数赋值
			pages = count / img.PAGE_SIZE + 1;
		}
		// 实例化StringBuffer
		StringBuffer sb = new StringBuffer();
		sb.append("<a href='FindImgServlet?page=1'>首页&nbsp;</a>");
		sb.append("&nbsp;&nbsp;");
		// 通过循环构建分页条
		for(int i=1; i <= pages; i++){
			// 判断是否为当前页
			if(i == currPage){
				// 构建分页条
				sb.append("『" + i + "』");
			}else{
				sb.append("<a href='FindImgServlet?page=" + i + "'>" + i + "</a>");
			}
			// 构建分页条
			sb.append("&nbsp;&nbsp;");
		}
		sb.append("<a href='FindImgServlet?page="+pages+"'>末页</a>");
		// 将分页条的字符串放置到request之中
		request.setAttribute("bar", sb.toString());
		// 转发到message.jsp页面
		request.getRequestDispatcher("message.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
